package atest.reopen.session.interceptor.sharding;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * @Description 参考：Mybatis的分表实战：https://www.cnblogs.com/mumuxinfei/p/9371986.html
 * @Author zenghua
 * @Email hua.zeng@dmall.com
 * @Date 2020/3/2 22:37
 * @Version 1.0
 */
@Intercepts({@Signature(
        type= Executor.class,
        method = "query",
        args = {MappedStatement.class,Object.class, RowBounds.class, ResultHandler.class})})
public class ShardingInterceptor implements Interceptor {
    public static final String SCHEMA_FILE_PATH = "schemaFilePath";
    //初始化脚本集合
    private List<String> schemaList;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //1、根据注解拿到数据库表
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        String id = ms.getId();
        String daoClassName = id.substring(0, id.lastIndexOf('.'));
        Class clazz = Class.forName(id);







        // 获取TableShard注解
        Sharding sharding = (Sharding)clazz.getAnnotation(Sharding.class);
        String sourceTableName = sharding.tableName();
        String targetTableName = null;
        for (String schema : schemaList) {
            //2、判断表在初始化的表里面没
            if (schema.contains(sourceTableName)) {
                Class<? extends ShardingHandler> handlerClazz = sharding.handlerClass();
                ShardingHandler shardingHandler = handlerClazz.newInstance();
                //3、根据处理器去生成表名字
                targetTableName = shardingHandler.handle(sourceTableName);

                //4、TODO 判断该表名是否存在数据库中，select count(*) from information_schema.TABLES where table_name = #{tableName}
                if (!isExistTableName(ms, schema, targetTableName)) {
                    //创建新的表名
                    createTable(ms, schema);
                    //5、替换表名字
                    Object parameter = args[1];
                    BoundSql boundSql = ms.getBoundSql(parameter);
                    String sourceSql = boundSql.getSql();
                    String shardingSql = sourceSql.replaceAll(sourceTableName, targetTableName);
                    Field field = boundSql.getClass().getDeclaredField("sql");
                    field.setAccessible(true);
                    field.set(boundSql, shardingSql);
                }
                break;
            };
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    //这里可以缓存表信息
    @Override
    public void setProperties(Properties properties) {
        String path = properties.getProperty(SCHEMA_FILE_PATH);
        //初始化table

        String tables = "create table t_student(\n" +
                "  id int not null auto_increment,\n" +
                "  stu_no varchar(20) comment '学号',\n" +
                "  nick_name varchar(20) comment '曾用名',\n" +
                "  real_name varchar(20) comment '真实名字',\n" +
                "  sex_type varchar(10) comment '性别',\n" +
                "  status varchar(10) comment '学籍状态',\n" +
                "  created_time datetime comment '创建时间',\n" +
                "  updated_time datetime comment '更新时间',\n" +
                "  primary key (id)\n" +
                ");";
        this.schemaList = Arrays.asList(tables.split(";"));

    }

    private boolean isExistTableName(MappedStatement mappedStatement, String schema, String targetTableName) throws SQLException {
        DataSource dataSource = mappedStatement.getConfiguration().getEnvironment().getDataSource();
        Connection connection = dataSource.getConnection();
        String existSql = "select count(*) from information_schema.TABLES where table_name = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(existSql);
        preparedStatement.setObject(1, targetTableName);
        ResultSet resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {
            int tableCount = resultSet.getInt(0);
            if (tableCount == 0) {
                return false;
            }
        }

        return true;
    }

    private void createTable(MappedStatement mappedStatement, String schema) throws SQLException {
        DataSource dataSource = mappedStatement.getConfiguration().getEnvironment().getDataSource();
        Connection connection = dataSource.getConnection();
        Statement statement = connection.createStatement();
        statement.execute(schema);
        statement.close();
    }
}
